var Students = function () {

    return {

        //main function to initiate the module
        init: function () {
            function restoreRow(oTable, nRow) {
                var aData = oTable.fnGetData(nRow);
                var jqTds = $('>td', nRow);

                for (var i = 0, iLen = jqTds.length; i < iLen; i++) {
                    oTable.fnUpdate(aData[i], nRow, i, false);
                }

                oTable.fnDraw();
            }

            function addRow(oTable, nRow) {
                var aData = oTable.fnGetData(nRow);
                var jqTds = $('>td', nRow);

                //jqTds[0].innerHTML = '<input type="text" class="form-control small" value="' + aData[0] + '">';
                jqTds[1].innerHTML = '<input type="text" class="form-control small" value="' + aData[1] + '">';
                jqTds[2].innerHTML = '<input type="checkbox" checked="" data-toggle="switch" />';
                jqTds[3].innerHTML = '<input type="text" onClick="WdatePicker({el:this, dateFmt:\'yyyy-MM-dd\'})"  class="Wdate" value="' + aData[3] + '">';
                jqTds[4].innerHTML = '<input type="text" class="form-control small" value="' + aData[4] + '">';
                jqTds[5].innerHTML = '<input type="text" class="form-control small" value="' + aData[5] + '">';

                jqTds[6].innerHTML = '<a class="add" href="">保存</a>';
                jqTds[7].innerHTML = '<a class="cancel" data-mode="new" href="">取消</a>';
            }

            function updateRow(oTable, nRow) {
                var aData = oTable.fnGetData(nRow);
                var jqTds = $('>td', nRow);

                //jqTds[0].innerHTML = '<input type="text" class="form-control small" value="' + aData[0] + '">';
                jqTds[1].innerHTML = '<input type="text" class="form-control small" value="' + aData[1] + '">';
                jqTds[2].innerHTML = '<input type="checkbox" checked="" data-toggle="switch" />';
                jqTds[3].innerHTML = '<input type="text" onClick="WdatePicker({el:this, dateFmt:\'yyyy-MM-dd\'})"  class="Wdate" value="' + aData[3] + '">';
                jqTds[4].innerHTML = '<input type="text" class="form-control small" value="' + aData[4] + '">';
                jqTds[5].innerHTML = '<input type="text" class="form-control small" value="' + aData[5] + '">';

                jqTds[6].innerHTML = '<a class="update" href="">保存</a>';
                jqTds[7].innerHTML = '<a class="cancel" href="">取消</a>';
            }

            function saveRow(oTable, nRow) {
                var jqInputs = $('input', nRow);
                var i = 0;

                //
                var sex = $('input[type="checkbox"]', nRow);

                for (; i < jqInputs.length; i++) {
                    oTable.fnUpdate(jqInputs[i].value, nRow, i + 1, false);
                }

                if (sex.is(':checked')){
                    oTable.fnUpdate('男', nRow, 2, false);
                } else {
                    oTable.fnUpdate('女', nRow, 2, false);
                }

                oTable.fnUpdate('<a class="edit" href="">编辑</a>', nRow, ++i, false);
                oTable.fnUpdate('<a class="delete" href="">删除</a>', nRow, ++i, false);

                oTable.fnDraw();
            }

            function cancelEditRow(oTable, nRow) {
                var jqInputs = $('input', nRow);
                oTable.fnUpdate(jqInputs[0].value, nRow, 0, false);
                oTable.fnUpdate(jqInputs[1].value, nRow, 1, false);
                oTable.fnUpdate(jqInputs[2].value, nRow, 2, false);
                oTable.fnUpdate(jqInputs[3].value, nRow, 3, false);
                oTable.fnUpdate('<a class="edit" href="">Edit</a>', nRow, 4, false);
                oTable.fnDraw();
            }

            function loadDatas(oTable) {
                $.ajax({
                    type: "post",
                    dataType: "json",
                    url: "/student/list",
                }).success(function (data) {
                    console.log(data);
                    if(data.code) {
                        var list = data.data;

                        for(var i = 0; i < list.length; i++) {
                            oTable.fnAddData([
                                list[i].sid,
                                list[i].sname,
                                list[i].genter === '1' ? '男' : '女',
                                list[i].birthday,
                                list[i].tellphone,
                                list[i].email,
                                '<td><a class="edit" href="javascript:;">编辑</a></td>',
                                '<td><a class="delete" href="javascript:;">删除</a></td>'
                            ], false);
                        }

                        oTable.fnDraw();
                    }

                });
            }

            var oTable = $('#editable-sample').dataTable({
                "aLengthMenu": [
                    [5, 15, 20, -1],
                    [5, 15, 20, "All"] // change per page values here
                ],
                // set the initial value
                "iDisplayLength": 15,
                "sDom": "<'row'<'col-lg-6'l><'col-lg-6'f>r>t<'row'<'col-lg-6'i><'col-lg-6'p>>",
                "sPaginationType": "bootstrap",
                "oLanguage": {
                    "sLengthMenu": "每页显示 _MENU_ 条记录",
                    "oPaginate": {
                        "sPrevious": "上一页",
                        "sNext": "下一页"
                    },
                    "sInfo": "从第 _START_ 条到第 _END_ 条, 共 _TOTAL_ 条",
                    "sEmptyTable": "没有数据"
                },
                "aoColumnDefs": [{
                        'bSortable': false,
                        'aTargets': [0]
                    }
                ]
            });

            loadDatas(oTable);

            jQuery('#editable-sample_wrapper .dataTables_filter input').addClass("form-control medium"); // modify table search input
            jQuery('#editable-sample_wrapper .dataTables_length select').addClass("form-control xsmall"); // modify table per page dropdown

            $('#editable-sample_new').click(function (e) {
                e.preventDefault();
                var aiNew = oTable.fnAddData(['', '', '', '', '', '',
                        '<a class="edit" href="">保存</a>', '<a class="cancel" data-mode="new" href="">取消</a>'
                ]);
                var nRow = oTable.fnGetNodes(aiNew[0]);
                addRow(oTable, nRow);
                nEditing = nRow;

                // Switch
                $("[data-toggle='switch']").wrap('<div class="switch" />').parent()
                    .data('on-label', '男').data('off-label', '女').bootstrapSwitch();
            });

            $('#editable-sample a.delete').live('click', function (e) {
                e.preventDefault();

                if (confirm("你确定要删除此行 ?") == false) {
                    return;
                }

                var nRow = $(this).parents('tr')[0];
                var aData = oTable.fnGetData(nRow);

                $.ajax({
                    type: "post",
                    dataType: "json",
                    url: "/student/delete",
                    data: { id: aData[0] }
                }).success(function (data) {
                    if (data.code) {
                        oTable.fnDeleteRow(nRow);
                    } else {
                        console.log("删除失败");
                        alert("删除失败");

                    }
                }).fail(function (data) {
                    console.error("error:", data);
                });

            });

            $('#editable-sample a.cancel').live('click', function (e) {
                e.preventDefault();

                if ($(this).attr("data-mode") == "new") {
                    var nRow = $(this).parents('tr')[0];
                    oTable.fnDeleteRow(nRow);
                } else {
                    restoreRow(oTable, nEditing);
                    nEditing = null;
                }
            });

            $('#editable-sample a.add').live('click', function (e) {
                e.preventDefault();

                /* Get the row as a parent of the link that was clicked on */
                var nRow = $(this).parents('tr')[0];

                saveRow(oTable, nRow);

                var aData = oTable.fnGetData(nRow);
                console.log(aData);

                $.ajax({
                    url: '/student/add',
                    dataType:'json',
                    type: 'post',
                    data: {
                        sname: aData[1],
                        genter: aData[2] === '男' ? '1' : '0',
                        birthday: aData[3],
                        tellphone: aData[4],
                        email: aData[5]
                    }
                }).success(function (data) {
                    console.log(data);
                    if(data.code){
                        oTable.fnUpdate(data.data, nRow, 0);
                    }
                });
            });

            $('#editable-sample a.update').live('click', function (e) {
                e.preventDefault();

                /* Get the row as a parent of the link that was clicked on */
                var nRow = $(this).parents('tr')[0];

                saveRow(oTable, nRow);

                var data = oTable.fnGetData(nRow);

                $.ajax({
                    url:'/student/update',
                    dataType: 'json',
                    type: 'post',
                    data:{
                        sid: data[0],
                        sname: data[1],
                        genter: data[2] === '男' ? '1' : '0',
                        birthday: data[3],
                        tellphone: data[4],
                        email: data[5]
                    }
                }).success(function (data) {
                    //console.log(data);
                    if (data.code) {
                        $("#success-model").modal();
                    }
                });
            });

            $('#editable-sample a.edit').live('click', function (e) {
                e.preventDefault();

                /* Get the row as a parent of the link that was clicked on */
                var nRow = $(this).parents('tr')[0];

                updateRow(oTable, nRow);

                // Switch
                $("[data-toggle='switch']").wrap('<div class="switch" />').parent()
                    .data('on-label', '男').data('off-label', '女').bootstrapSwitch();
            });
        }

    };

}();